package org.amos.msg.platform;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import org.amos.msg.enums.MsgPlatformEnum;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class MsgPlatformManager {

    /**
     * key: platform唯一标识
     */
    private final ConcurrentMap<String, AbstractMsgPlatform> platformMap = new ConcurrentHashMap<>();

    public <T extends MsgPlatformConfig> AbstractMsgPlatform<T> getPlatform(String platformId, String platform, T config) {
        AbstractMsgPlatform<T> msgPlatform = platformMap.get(platformId);
        if (msgPlatform == null) {
            msgPlatform = this.createmsgPlatform(platformId, platform, config);
            platformMap.put(platformId, msgPlatform);
        }
        if (msgPlatform.init(config)) {
            platformMap.put(platformId, msgPlatform);
        }

        return msgPlatform;
    }

    private <T extends MsgPlatformConfig> AbstractMsgPlatform<T> createmsgPlatform(String platformId, String platform, T config) {
        MsgPlatformEnum platformEnum = MsgPlatformEnum.getByPlatform(platform);
        Assert.notNull(platformEnum, String.format("文件配置(%s) 为空", platformEnum));
        // 创建客户端
        return (AbstractMsgPlatform<T>) ReflectUtil.newInstance(platformEnum.getClientClass(), platformId, config);
    }
}
